#coding=utf-8

from django.db import models
from django.contrib.auth.models import User

from question.models import Question
from star.models import Star

class VoteManager(models.Manager):
	pass

class Vote(models.Model):
    AGREE = 1
    NEUTRAL = 2
    DISAGREE = 3
    VOTE_CHOICES = ((AGREE,'agree') ,(NEUTRAL, u'neutral'), (DISAGREE, u'disagree'))

    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)
    result = models.IntegerField(choices=VOTE_CHOICES, default=AGREE, verbose_name=u"投票结果") 
    has_opinion = models.BooleanField(default=False, verbose_name=u'是否有建议')
    is_star = models.BooleanField(default=False, verbose_name=u'是否有加星')
    opinion = models.TextField(verbose_name=u'建议')
    created_time = models.DateTimeField(auto_now_add=True)	
        
    objects = VoteManager()

    class Meta:
        verbose_name = u'投票'
        verbose_name_plural = u'投票列表'
        unique_together = ("user", "question") 
        db_table = "t_vote"
        ordering = ["-created_time"]
        
    def save(self):
        created = False
        if not self.id:
            created = True
        super(Vote, self).save()
        if created:
            try:
                vote_stat = self.question.votestat
            except VoteStat.DoesNotExist:
                vote_stat = VoteStat(question=self.question)
            vote_stat.vote_count += 1
            if self.result == self.AGREE:
                vote_stat.agree_count += 1
            elif self.result == self.DISAGREE:
                vote_stat.disagree_count +=1
            else:
                vote_stat.neutral_count += 1
            vote_stat.save()
                
    def add_star(self):
        if not self.is_star:
            self.is_star = True
            self.save()
            Star.objects.add(self)
            

class VoteStatManager(models.Manager):
	pass

class VoteStat(models.Model):
    question = models.OneToOneField(Question, unique=True)
    vote_count = models.IntegerField(default=0, verbose_name=u"vote_count")   
    agree_count = models.IntegerField(default=0, verbose_name=u"agree_count")    
    disagree_count = models.IntegerField(default=0, verbose_name=u"disagree_count")       
    neutral_count =  models.IntegerField(default=0, verbose_name=u"neutral_count")     
    created_time = models.DateTimeField(auto_now_add=True)	
    updated_time = models.DateTimeField(auto_now=True)
    
    objects = VoteStatManager()
    
    class Meta:
        verbose_name = u'投票统计'
        verbose_name_plural = u'投票统计列表'
        db_table = "t_vote_stat"
        ordering = ["-created_time"]		